// pages/find/activity/join.js
const config = getApp().globalData.config
const T = getApp().globalData.T
let token = ''
let userId = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: -1,
    inputItem: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.id = options.id;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    token = getApp().globalData.token;
    userId = getApp().globalData.userId;
    this.getDetail();
  },

  getDetail() {
    T.req({
      loadTitle: '初始化中...',
      url: config.api + 'forum/topic/activity/' + this.data.id,
      method: 'GET',
      data: {
        token: token
      },
      success: (res) => {
        this.setData({ list: res });
      }
    })
  },

  onInput(e) {
    let type = e.currentTarget.dataset.type;
    let index = e.currentTarget.dataset.index;
    let value = e.detail.value;

    this.data.inputItem.splice(index, 1, {
      type: Number(type),
      item: value
    })
  },

  onSubmit() {
    let temArr = this.data.inputItem;
    let isError = false;
    let errTxt = '';

    if (this.data.list.length != temArr.length) {
      T.toast({ id: '#toast', text: '还有选项没有填写,请检查' });
      return
    };

    temArr.forEach(m => {
      switch (m.type) {
        case 1:  // 电话
          if (!T.regExp.tel.test(m.item)) {
            isError = true;
            errTxt = '电话格式不对'
          }
          break;
        case 2:  // 邮箱
          if (!T.regExp.email.test(m.item)) {
            isError = true;
            errTxt = '邮箱格式不对'
          }
          break;
      }
    });
    if (isError) {
      T.toast({ id: '#toast', text: errTxt });
      return;
    }

    T.req({
      loadTitle: '请求中...',
      url: config.api + 'forum/topic/activity?token=' + token,
      method: 'POST',
      data: {
        userId: userId,
        actId: this.data.id,
        list: temArr
      },
      success: (res) => {
        T.toast({
          id: '#toast', text: '报名成功', success: () => {
            wx.navigateBack({
              delta: 1
            })
          }
        });
      }
    })
  }

})